package com.lsy.android.pingpang.view;

import com.lsy.android.pingpang.R;
import com.lsy.android.pingpang.bluetooth.DataBean;
import com.lsy.android.pingpang.tool.MyTimer;
import com.lsy.android.pingpang.tool.SharePerenceHelp;

import android.app.Activity;
import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.MediaPlayer;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

public abstract class GameView extends FrameLayout {

	/** 球的x速度 */
	private float ballSpeedX;
	/** 球的y速度 */
	private float ballSpeedY;
	private float k;
	/** 级别 */
	private int level;

	/** player1分数 */
	public int placar1;
	/** player2分数 */
	public int placar2;
	/** 运行状态 */
	public int roda;
	/** 屏幕宽 */
	public int xMax;
	/** 屏幕高 */
	public int yMax;
	/** player1球拍的y位置 */
	public float Meio1;
	/** player2球拍的y位置 */
	public float Meio2;
	private RectF ballBounds;
	private static final float ballRadius = 10F;
	public float ballX;
	public float ballY;
	private Activity mActivity;
	private Paint paint;
	/** player1球拍图形 */
	private RectF raquete1;
	/** player2球拍图形 */
	private RectF raquete2;
	/** 球拍长度 */
	private int tamanhoRaquete;

	private Paint scorePaint;
	private Paint playerNamePaint;
	private Paint tinta5;
	private static final int xMin = 0;
	private static final int yMin = 0;

	private Bitmap mBallBmp;
	private Rect mBallScrRect;
	private Bitmap mBatBmp1;
	private Rect mBatScrRect1;
	private Bitmap mBatBmp2;
	private Rect mBatScrRect2;
	private Bitmap mTitleBmp;

	private MediaPlayer mSoundGol;
	private MediaPlayer mSoundParede;
	private MediaPlayer mSoundRaquete;

	private long lastTime;
	private int count = 4;

	private boolean isAutoUpdateBat = false;
	public int gameMode;
	// 蓝牙游戏适用
	public int soundType;
	// 蓝牙游戏适用
	public String time;
	private boolean showStartButton = false;
	private boolean isPause;
	private int gameViewStyle = 0;

	public GameView(Activity activity) {
		super(activity);
		gameMode = SharePerenceHelp.getGameMode(activity);
		isAutoUpdateBat = autoUptateBat();
		showStartButton = showStartButton();
		gameViewStyle = getGameViewStyle();
		placar1 = 0;
		placar2 = 0;
		roda = 0;
		ballBounds = new RectF();
		paint = new Paint();
		raquete1 = new RectF();
		raquete2 = new RectF();

		scorePaint = new Paint();
		scorePaint.setTextSize(30F);
		scorePaint.setColor(Color.YELLOW);
		playerNamePaint = new Paint();
		playerNamePaint.setColor(0x40ffffff);
		playerNamePaint.setTextSize(30F);
		tinta5 = new Paint();
		tinta5.setColor(0x18ffffff);
		tinta5.setTextSize(25F);
		mActivity = activity;

		mSoundRaquete = MediaPlayer.create(mActivity, R.raw.parede);
		mSoundGol = MediaPlayer.create(mActivity, R.raw.gol);
		mSoundParede = MediaPlayer.create(mActivity, R.raw.raquete);

		mBallBmp = BitmapFactory.decodeResource(mActivity.getResources(),
				R.drawable.qiu);
		mBallScrRect = new Rect(0, 0, mBallBmp.getWidth(), mBallBmp.getHeight());

		Bitmap bmpBat1 = BitmapFactory.decodeResource(mActivity.getResources(),
				R.drawable.qiupai);
		Matrix matrix1 = new Matrix();
		mBatBmp1 = Bitmap.createBitmap(bmpBat1, 0, 0, bmpBat1.getWidth(),
				bmpBat1.getHeight(), matrix1, true);
		mBatScrRect1 = new Rect(0, 0, mBatBmp1.getWidth(), mBatBmp1.getHeight());

		Bitmap bmpBat2 = BitmapFactory.decodeResource(mActivity.getResources(),
				R.drawable.qiupai);
		Matrix matrix2 = new Matrix();
		matrix2.setRotate(180);
		mBatBmp2 = Bitmap.createBitmap(bmpBat2, 0, 0, bmpBat2.getWidth(),
				bmpBat2.getHeight(), matrix2, true);
		mBatScrRect2 = new Rect(0, 0, mBatBmp2.getWidth(), mBatBmp2.getHeight());

		mTitleBmp = BitmapFactory.decodeResource(mActivity.getResources(),
				getTitleDrawableId());

		setBackgroundResource(R.drawable.background);
		initLevel(SharePerenceHelp.getLevel(activity));

		showGameStartDialog();

	}

	public void GamePause() {
		isPause = true;
		MyTimer.getInstance().pause();
	}

	public void GameContinue() {
		isPause = false;
		MyTimer.getInstance().goOn();
	}

	public DataBean getDataBean() {
		return new DataBean(Meio1, Meio2, placar1, placar2, roda, xMax, yMax,
				ballX, ballY, soundType, gameMode, MyTimer.getInstance()
						.getStringTotalTime());
	}

	abstract int getGameViewStyle();

	abstract String getPlayer1Name();

	abstract String getPlayer2Name();

	abstract int getTitleDrawableId();

	abstract boolean showStartButton();

	@Override
	protected void onDraw(Canvas canvas) {
		// 画玩家名字
		drawPlayerName(canvas);
		// 画界面标题
		drawTitleImage(canvas);
		if (gameMode == 1) {
			// 画倒计时
			drawTimer(canvas);
		}
		// 画分数
		drawScore(canvas);
		// 画球拍
		drawBat(canvas);
		// 画球
		drawBall(canvas);

		// 更新球和球拍的位置

		if (gameMode == 1) {
			if (MyTimer.getInstance().getTotalTime() <= 0) {
				ballY = yMax / 2;
				ballX = xMax / 2;
				ballSpeedX = 0F;
				roda = 0;
				MyTimer.getInstance().pause();
				if (placar1 > placar2) {
					showGameOverDialog(1);
				} else if (placar1 < placar2) {
					showGameOverDialog(0);
				} else {
					showGameOverDialog(2);
				}
			} else {
				if (roda == 1) {
					if (!isPause) {
						update();
					}
				} else if (roda == 3) {
					drawPrepareTime(canvas, String.valueOf(count));
					if (System.currentTimeMillis() - lastTime > 1000) {
						count--;
						lastTime = System.currentTimeMillis();
						if (count == 0) {
							roda = 1;
							count = 4;
							drawPrepareTime(canvas, "开始");
							if (MyTimer.getInstance().isRunning()) {
								MyTimer.getInstance().goOn();
							} else {
								MyTimer.getInstance().start();
							}
						}
					}
				}
				invalidate();
			}
		} else {
			if (placar1 == 5 || placar2 == 5) {
				ballY = yMax / 2;
				ballX = xMax / 2;
				ballSpeedX = 0F;
				roda = 0;
				MyTimer.getInstance().pause();
				if (placar1 > placar2) {
					showGameOverDialog(1);
				} else if (placar1 < placar2) {
					showGameOverDialog(0);
				}
			} else {
				if (roda == 1) {
					if (!isPause) {
						update();
					}
				} else if (roda == 3) {
					drawPrepareTime(canvas, String.valueOf(count));
					if (System.currentTimeMillis() - lastTime > 1000) {
						count--;
						lastTime = System.currentTimeMillis();
						if (count == 0) {
							roda = 1;
							count = 4;
							drawPrepareTime(canvas, "开始");
						}
					}
				}
				invalidate();
			}
		}

	}

	private void drawPrepareTime(Canvas canvas, String value) {
		canvas.save();
		canvas.rotate(180, xMax / 2, yMax / 2);
		canvas.drawText(value, xMax / 2 - 7, yMax / 2 + 50, playerNamePaint);
		canvas.restore();
		canvas.drawText(value, xMax / 2 - 7, yMax / 2 + 50, playerNamePaint);
	}

	private void drawBall(Canvas canvas) {
		ballBounds.set(ballX - ballRadius - 5F, ballY - ballRadius - 5F, ballX
				+ ballRadius + 5F, ballY + ballRadius + 5F);
		canvas.drawBitmap(mBallBmp, mBallScrRect, ballBounds, paint);
	}

	private void drawBat(Canvas canvas) {
		raquete1.set(Meio2 - (float) tamanhoRaquete, 55F, Meio2
				+ (float) tamanhoRaquete, 155F);
		raquete2.set(Meio1 - (float) tamanhoRaquete, yMax - 155, Meio1
				+ (float) tamanhoRaquete, yMax - 55);
		// 画player1球拍
		canvas.drawBitmap(mBatBmp1, mBatScrRect1, raquete1, paint);
		// 画player2球拍
		canvas.drawBitmap(mBatBmp2, mBatScrRect2, raquete2, paint);
	}

	private void drawScore(Canvas canvas) {
		canvas.save();
		canvas.rotate(90, xMax / 2, yMax / 2);
		canvas.drawText(String.valueOf(placar1), xMax / 2 - 50F, yMax / 2
				- (xMax / 2 - 80F), scorePaint);
		canvas.drawText(":", xMax / 2, yMax / 2 - (xMax / 2 - 80F), scorePaint);
		canvas.drawText(String.valueOf(placar2), xMax / 2 + 30F, yMax / 2
				- (xMax / 2 - 80F), scorePaint);
		canvas.restore();
	}

	private void drawPlayerName(Canvas canvas) {
		canvas.save();
		canvas.rotate(90, xMax / 2, yMax / 2);
		canvas.drawText(getPlayer1Name(), xMax / 2 - 300, yMax / 2
				- (xMax / 2 - 80F), playerNamePaint);
		canvas.drawText(getPlayer2Name(), xMax / 2 + 250, yMax / 2
				- (xMax / 2 - 80F), playerNamePaint);
		canvas.restore();
	}

	private void drawTimer(Canvas canvas) {
		canvas.save();
		canvas.rotate(180, xMax / 2, yMax / 2);
		canvas.drawText(MyTimer.getInstance().getStringTotalTime(), 50,
				yMax - 50, playerNamePaint);
		canvas.restore();
		canvas.drawText(MyTimer.getInstance().getStringTotalTime(), 50,
				yMax - 50, playerNamePaint);
	}

	private void drawTitleImage(Canvas canvas) {
		canvas.drawBitmap(mTitleBmp, xMax - 150, yMax - 50, paint);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getY() > (float) (yMax * 3 / 4)) {
			Meio1 = event.getX();
		}
		return true;
	}

	@Override
	public void onSizeChanged(int w, int h, int oldw, int oldh) {
		xMax = w - 1;
		yMax = h - 1;
		Meio1 = xMax / 2;
		Meio2 = xMax / 2;
		ballX = xMax / 2;
		ballY = yMax / 2;
		tamanhoRaquete = 2 + xMax / 7;
	}

	@Override
	protected void onDetachedFromWindow() {
		if (gameMode == 1) {
			MyTimer.getInstance().stop();
		}
		if (mSoundRaquete != null) {
			mSoundRaquete.release();
			mSoundRaquete = null;
		}
		if (mSoundGol != null) {
			mSoundGol.release();
			mSoundGol = null;
		}
		if (mSoundParede != null) {
			mSoundParede.release();
			mSoundParede = null;
		}
		if (mBallBmp != null) {
			mBallBmp.recycle();
			mBallBmp = null;
		}
		if (mBatBmp1 != null) {
			mBatBmp1.recycle();
			mBatBmp1 = null;
		}
		if (mBatBmp2 != null) {
			mBatBmp2.recycle();
			mBatBmp2 = null;
		}
		super.onDetachedFromWindow();
	}

	abstract boolean autoUptateBat();

	private void update() {
		ballX = ballX + ballSpeedX;
		ballY = ballY + ballSpeedY;
		if (isAutoUpdateBat) {
			// 球拍自动移动
			if (ballY < (float) ((3 * yMax) / 4)) {
				if (Meio2 < ballX - (float) level) {
					Meio2 = Meio2 + (float) level;
				} else if (Meio2 > ballX + (float) level) {
					Meio2 = Meio2 - (float) level;
				}
			}
		}
		// 球碰到右边
		if (ballX + ballRadius > (float) xMax) {
			ballSpeedX = -ballSpeedX;
			ballX = (float) xMax - ballRadius;
			if (mSoundParede != null) {
				mSoundParede.start();
			}
		} else if (ballX - ballRadius < (float) xMin) {// 球碰到左边
			ballSpeedX = -ballSpeedX;
			ballX = (float) xMin + ballRadius;
			if (mSoundParede != null) {
				mSoundParede.start();
			}
		}
		// 球碰到下球拍
		if (ballY + ballRadius > (float) (yMax - 155)) {
			if ((ballX - Meio1) * (ballX - Meio1) < (float) ((8 + tamanhoRaquete) * (8 + tamanhoRaquete))
					&& ballY + ballRadius < (float) (yMax - 60 - 10)
							+ ballSpeedY) {
				ballSpeedY = -ballSpeedY;
				ballSpeedX = (ballX - Meio1) / k;
				ballY = (float) (yMax - 155) - ballRadius;
				if (mSoundRaquete != null) {
					mSoundRaquete.start();
				}
			}
		} else if (ballY - ballRadius < (float) (155 + yMin)// 球碰到上球拍
				&& (ballX - Meio2) * (ballX - Meio2) < (float) ((8 + tamanhoRaquete) * (8 + tamanhoRaquete))
				&& ballY - ballRadius > (float) (10 + yMin) + ballSpeedY) {
			ballSpeedY = -ballSpeedY;
			if (ballSpeedX > 0.0F) {
				ballSpeedX = ballSpeedX - 70F / k;
			} else {
				ballSpeedX = 70F / k + ballSpeedX;
			}
			ballY = (float) (155 + yMin) + ballRadius;
			if (mSoundRaquete != null) {
				mSoundRaquete.start();
			}
		}

		// 球下边出界
		if (ballY + ballRadius > (float) (yMax - 15)) {
			ballY = yMax / 2;
			ballX = xMax / 2;
			placar1 = 1 + placar1;
			ballSpeedX = 0F;
			roda = 0;
			if (mSoundGol != null) {
				mSoundGol.start();
			}
			if (gameMode == 1) {
				MyTimer.getInstance().pause();
			}
			showGameStartDialog();
		} else if (ballY - ballRadius < (float) (yMin - 15)) {// 球上边出界
			ballY = yMax / 2;
			ballX = xMax / 2;
			placar2 = 1 + placar2;
			ballSpeedX = 0F;
			roda = 0;
			if (mSoundGol != null) {
				mSoundGol.start();
			}
			if (gameMode == 1) {
				MyTimer.getInstance().pause();
			}
			showGameStartDialog();
		}
	}

	public void initLevel(int value) {
		switch (value) {
		case 0:
			ballSpeedY = 8F;
			level = 2;
			k = 13F;
			break;
		case 1:
			ballSpeedY = 13F;
			level = 5;
			k = 5F;
			break;
		case 2:
			ballSpeedY = 18F;
			level = 13;
			k = 3F;
			break;
		case 3:
			ballSpeedY = 21F;
			level = 16;
			k = 2F;
			break;
		case 4:
			ballSpeedY = 30F;
			level = 20;
			k = 1F;
			break;
		default:
			ballSpeedY = 8F;
			level = 2;
			k = 13F;
			break;
		}
		ballSpeedX = 0F;
	}

	private void showGameStartDialog() {
		if (showStartButton) {
			final LinearLayout view = new LinearLayout(mActivity);
			view.setGravity(Gravity.CENTER);
			view.setLayoutParams(new FrameLayout.LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
			Button button = new Button(mActivity);
			view.addView(button);
			button.setLayoutParams(new LinearLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
			button.setBackgroundResource(R.drawable.btn_faqiu);
			button.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (roda == 0) {
						roda = 3;
					}
					removeView(view);
				}
			});
			addView(view);
		}
	}

	private void showGameOverDialog(int style) {
		final Dialog dialog = new Dialog(getContext(), R.style.gameover_dialog);
		dialog.setContentView(new GameOverView(mActivity, style, this, dialog,gameViewStyle));
		dialog.show();
	}

}
